home *** CD-ROM | disk | FTP | other *** search
- Path: svnews.ubinet.ubs.com!ubszh!ian.johnston@ubs.com
- From: ian.johnston@ubs.com (Ian Johnston (by ubsswop))
- Newsgroups: comp.lang.c++
- Subject: Re: Creating an object via new with ONLY a pointer to the object
- Date: 12 Apr 1996 07:20:25 GMT
- Organization: UBS
- Distribution: world
- Message-ID: <4kl07p$bpm@ubszh.fh.zh.ubs.com>
- References: <4kh07v$lno@crchh327.rich.bnr.ca> <316D04B3.41C6@meca.polymtl.ca>
- NNTP-Posting-Host: nol2179.fh.zh.ubs.com
-
- In article <316D04B3.41C6@meca.polymtl.ca>, Pierre Ferland <pierre@meca.polymtl.ca> writes:
- |> Bret Bieghler wrote:
-
- [On creating instances of derived classes, given a key, such as a class name]
-
- |> What you need is a virtual constructor, that is a pure virtual
- |> function declared in the base class:
- |>
- |> class CommandObject_c {
- |>
- |> public:
- |> virtual CommandObject_c *VirtualConstruct(void)=0;
- |>
- |> };
- |>
- |> class ExitCommand_c {
- |> public:
- |> // Copy constructor, needed in virtual constructor
- |> ExitCommand_c(ExitCommand_c&);
- |>
- |> // virtual constructor
- |> CommandObject_c *VirtualConstruct(void) {
- |> return new ExitCommand_c(*this);
- |> }
- |> };
- |> and implemented in the derived classes:
- |>
- |> class ExitCommand_c {
- |> public:
- |> // Copy constructor, needed in virtual constructor
- |> ExitCommand_c(ExitCommand_c&);
- |>
- |> // virtual constructor
- |> CommandObject_c *VirtualConstruct(void) {
- |> return new ExitCommand_c(*this);
- |> }
- |> };
- |>
- |> When you handle a pointer
- |> to a base class object (thus using polymorphisms), the only entity
- |> that can realize the cloning operation is the derived object itself,
- |> since he's the only one to know ``what he is''.
- |> The only counterpart in that is that if you design very
- |> complicated (avoid) class family trees with multiple inheritence,
- |> there might be ambiguities. In such a case, my advice is
- |> to re-design the families and use containers and interfaces
- |> to simplify the class diagram. Some other approaches can
- |> lead to ugly situations!
-
- This won't work. You would need an instance of ExitCommand on which to
- call the VirtualConstruct() function.
-
- But the whole point is how to create an instance of ExitCommand in the
- first place!
-
- Ian
-